<template>
	<view>
		<view class="save" v-if="!savedFlag">
			<evaluate-info ref="evaluateRef" v-if="isNotNull(targetsData) && targetsData.length>0"
				:target-data="targetsData" :comments-data="commentsData"></evaluate-info>
		</view>

		<view class="view record-container" v-else>

			<view class="" style="z-index: 1000; position: fixed; top: 0; left: 0; right: 0;">
				<view class="" v-show="targets.length>1"
					style="display: flex; justify-content: center; align-items: center; height: 30px; background-color: #F2F2F0;">
					<text>左右滑动切换不同指标页面</text>
				</view>
				<view class=""
					style="display: flex; justify-content: center; align-items: center; background-color: #fff; height: 35px;">
					<text
						style="margin-left: 5px; display: inline-block; display: flex; justify-content: center; align-items: center; height: 30px; width: 30px; border-radius: 50%;"
						v-for=" (item,index1) in targets.length" :key="index1"
						:style="index1 === index ? 'background-color: #3288DF;': 'background-color: #CCCCCC;'">
						{{index1+1}}</text>
				</view>
			</view>
			<view class="" style="background-color: #fff;" :style="{height: (targets.length> 1? '60px': '30px') }">

			</view>
			<swiper class="swiper" :indicator-dots="false" :autoplay="false" duration="500">
				<swiper-item v-for="(target,index) in targets" :key="target.id">
					<wyb-slide-listener @slideLeft="onSlide" @slideRight="onSlide">
						<!-- 此处放你要监听的内容 -->
						<uni-forms :ref="'targetForm'+index" :modelValue="target" label-position="top">
							<uni-forms-item label="指标名称" name="name">
								<uni-easyinput v-model="target.name" disabled />
							</uni-forms-item>
							<uni-forms-item label="活动时间" name="createTime">
								<uni-easyinput v-model="target.createTime" disabled />
							</uni-forms-item>
							<uni-forms-item label="指标说明" name="content">
								<uni-easyinput type="textarea" disabled v-model="target.content" />
							</uni-forms-item>

							<uni-forms-item label="评价结果" name="result">
								<uni-easyinput type="textarea" v-model="target.result" disabled />
							</uni-forms-item>

							<uni-forms-item label="审核评价" name="remark" v-if="target.commentRemark.length > 0">
								<uni-list>
									<uni-list-item v-for="(item, index2) in target.commentRemark" :key="index2"
										:title="item.content">
										<template v-slot:body>
											<text class="slot-box slot-text">{{item.content}}</text>
										</template>
										<template v-slot:footer>
											<image class="slot-image" :src="getSrc(item.state)" mode="widthFix"
												style="height: 25px;width: 25px;margin-left: auto;"></image>
										</template>
									</uni-list-item>
								</uni-list>
							</uni-forms-item>
						</uni-forms>
					</wyb-slide-listener>

				</swiper-item>
			</swiper>
			<view class="media">
				<u-cell-group>
					<u-cell isLink icon="file-text-fill" title="实证资料" @click="viewFile">
						<u-badge slot="value" :showZero="true" :value="fileNum"></u-badge>
					</u-cell>
				</u-cell-group>
			</view>
		</view>


	</view>
</template>

<script>
	import {
		deepClone,
		isNotNull
	} from "@/utils/common.js"
	import {
		getTarget,
		savePendingSchoolComment,
		addSchoolComment
	} from '@/api/school/index.js'
	// 引入上传文件接口
	import {
		uploadUrl,
	} from "@/api/supervise/index.js"
	export default {
		data() {
			return {
				activityId: "",
				index: 0,
				// 活动指标id
				targetId: "",
				targetsData: [],
				commentsData: [],
				finishState: "",
				// 是否已经保存标志
				changeBtnTitleFlag: false,
				savedFlag: false,
				// 提交后展示的数据
				targets: [],
				comments: [],
				fileNum: 0,
				storageKey: '',
				isNotNull,
				uploadUrl
			}
		},
		computed: {
			schoolId() {
				return this.$store.state.user.schoolId
			}
		},
		methods: {
			submit() {
				const ref = this.$refs.evaluateRef;
				ref.validate(({
					valid,
					error,
					formData,
					originalData
				}) => {
					console.log(originalData)
					console.log(formData)
					console.log(valid)


					if (valid) {

						/**
						 * 判断网络状态，如果有网络，直接保存，没有网络，先缓存在本地
						 * 等待有网络的时候，下次用这个设备保存
						 */
						uni.getNetworkType({
							success: (res) => {
								if (res.networkType === 'none') { //网络不通，缓存在本地
									this.saveStore(originalData)

								} else { // 提交服务器

									// 如果保存过了，提交就保存照片了
									new Promise((resolve, reject) => {
										let saveData = [];
										const data = deepClone(formData)
										data.forEach(async (item, index) => {
											if (item.files && item.files.length >
												0) {
												await this.uploadFile(item.files)
													.then(
														res => {
															const newData = {
																...item,
																activityId: this
																	.activityId,
																schoolId: this
																	.schoolId,
																urlId: res
															};
															delete newData.files;
															saveData.push(newData);
														});
											} else {
												const newData = {
													...item,
													activityId: this
														.activityId,
													schoolId: this.schoolId,
												};
												delete newData.files;
												saveData.push(newData);
											}
											if (index === formData.length - 1) {
												resolve(saveData);
											}
										});
									}).then(comments => {
										console.log(comments)

										if (!this.changeBtnTitleFlag) {
											console.log("准备保存")

											// 当标志为false,表示未提交
											savePendingSchoolComment(comments).then(res => {
												uni.removeStorage({
													key: this.storageKey
												});
												uni.$u.toast(res.result);
												this.changeNaBtnTitle("提交")
												this.changeBtnTitleFlag = true
											})
										} else {
											console.log("准备提交")
											addSchoolComment(comments).then(res => {
												uni.removeStorage({
													key: this.storageKey
												});
												uni.$u.toast(res.result);
												this.changeNaBtnTitle("提交了")
											})
										}
									});
								}
							}
						})
					} else {
						uni.$u.toast('还存在必填项未填写');
						return;
					}
				})
			},
			onSlide: function(e) {
				let type = e.type
				switch (type) {
					case 'slideLeft':
						if (this.index < this.targets.length - 1) {
							this.index++;
							this.getFileNum();
						}
						break
					case 'slideRight':
						if (this.index > 0) {
							this.index--;
							this.getFileNum();
						}
						break
				}
			},

			getTargetContent() {

				uni.getStorage({
					key: this.storageKey,
					success: (res) => {
						console.log("success")
						const data = deepClone(res.data);
						console.log(data)
						let commentsData = []
						let targetsData = []
						data.forEach(item => {
							if (item.comment) {
								let comment = deepClone(item.comment);
								comment.targetId = item.comment.targetId || item.id
								if (comment.storeageFiles && comment.storeageFiles.length > 0) {
									const imageFiles = comment.storeageFiles.filter(item => {
										return item.type === 'image'
									}).map(item => {
										let url = item.url;
										const name = url.split("/");
										const fileName = name[name.length - 1];
										return {
											url: url,
											name: fileName,
											extname: fileName.split(".")[1]
										};
									})
									const voiceFiles = comment.storeageFiles.filter(item => {
										return item.type === 'voice'
									}).map(item => {
										let url = item.url;
										const name = url.split("/");
										const fileName = name[name.length - 1];
										return {
											url: url,
											name: fileName,
											extname: fileName.split(".")[1]
										};
									})
									const videoFiles = comment.storeageFiles.filter(item => {
										return item.type === 'video'
									}).map(item => {
										let url = item.url;
										const name = url.split("/");
										const fileName = name[name.length - 1];
										return {
											url: url,
											name: fileName,
											extname: fileName.split(".")[1]
										};
									})
									console.log(comment.uuid)
									this.$store.commit('SAVE_PIC', {
										uuid: comment.uuid,
										files: {
											originFiles: [],
											appendFiles: imageFiles
										}
									})
									this.$store.commit('SAVE_VIDEO', {
										uuid: comment.uuid,
										files: {
											originFiles: [],
											appendFiles: videoFiles
										}
									})
									this.$store.commit('SAVE_VOICE', {
										uuid: comment.uuid,
										files: {
											originFiles: [],
											appendFiles: voiceFiles
										}
									});
								}
								commentsData.push(comment);
								delete item.comment;
							}

							targetsData.push(item)
						})
						this.targetsData = targetsData;
						this.commentsData = commentsData;
					},
					fail: (err) => {
						console.log("fail");
						getTarget(this.schoolId, this.activityId, this.targetId).then(res => {
							console.log(res)
							// 1.展示表单
							this.targetsData = res.targets
							// 设置一个标志位,判断按钮文字
							if (res.comments.length > 0) {
								this.changeBtnTitleFlag = true
								if (res.comments[0].commitState === 0) {
									// 保存过，但是没有提交
									// 这里处理他们后端图片多逗号问题
									res.comments.forEach(item => {
										const imgUrl = isNotNull(item.imgUrl) ?
											item.imgUrl.substr(0, item.imgUrl.length - 1) :
											'';
										item["imgUrls"] = imgUrl.split(",");
										item["imgUrl"] = imgUrl;

										const voiceUrl = isNotNull(item.voiceUrl) ?
											item.voiceUrl.substr(0, item.voiceUrl.length - 1) :
											'';
										console.log(voiceUrl)
										item["voiceUrls"] = voiceUrl.split(",");
										item["voiceUrl"] = voiceUrl;

										const videoUrl = isNotNull(item.videoUrl) ?
											item.videoUrl.substr(0, item.videoUrl.length - 1) :
											'';
										item["videoUrls"] = videoUrl.split(",");
										item["videoUrl"] = videoUrl;


									})
									// 展示表单内容
									this.commentsData = res.comments
									this.changeNaBtnTitle("提交");
								} else {
									// 提交过后,不再使用第一个展示方式,重新构建数据
									let targets = res.targets
									let comments = res.comments
									for (let i = 0; i < targets.length; i++) {

										for (let j = 0; j < comments.length; j++) {

											if (comments[j].targetId == targets[i].id) {
												targets[i].commentRemark = comments[j].commentRemark
												targets[i].createTime = comments[j].createTime
												targets[i].improveState = comments[j].improveState
												targets[i].result = this.getResult(comments[j])
											}

										}

									}

									this.targets = targets;
									this.comments = comments;

									this.comments.forEach(item => {
										const imgUrl = isNotNull(item.imgUrl) ?
											item.imgUrl.substr(0, item.imgUrl.length - 1) :
											'';
										item["imgUrls"] = imgUrl.split(",");
										item["imgUrl"] = imgUrl;

										const voiceUrl = isNotNull(item.voiceUrl) ?
											item.voiceUrl.substr(0, item.voiceUrl.length - 1) :
											'';
										console.log(voiceUrl)
										item["voiceUrls"] = voiceUrl.split(",");
										item["voiceUrl"] = voiceUrl;

										const videoUrl = isNotNull(item.videoUrl) ?
											item.videoUrl.substr(0, item.videoUrl.length - 1) :
											'';
										item["videoUrls"] = videoUrl.split(",");
										item["videoUrl"] = videoUrl;


									})
									this.getFileNum()

									// 已经提交过了
									this.changeNaBtnTitle("提交了");
								}
							}
						})
					}
				});
			},
			async saveFile(files) {
				const saveFiles = deepClone(files);
				let newFiles = [];
				return new Promise((resolve, reject) => {
					if (saveFiles) {
						saveFiles.forEach(async (file, fileIndex) => {
							await uni.saveFile({
								tempFilePath: file.url,
								success: function(res) {
									plus.io.requestFileSystem(plus.io.PRIVATE_DOC,
										function(fs) {
											newFiles.push({
												type: file.type,
												url: fs.root.fullPath + (
													res.savedFilePath
													.replace("_doc/",
														""))
											})
											if (fileIndex === saveFiles.length -
												1) {
												resolve(newFiles);
											}
										},
										function(e) {
											console.log(
												"Request file system failed: " +
												e.message);
											uni.$u.toast("实证材料保存失败");
											return;
										});
								}
							});
						})
					} else {
						resolve()
					}
				});
			},
			saveStore(data) {
				//先判断是否已经有缓存，有的话先删除
				const storeageValue = uni.getStorageSync(this.storageKey);
				if (storeageValue) {
					uni.removeStorageSync(this.storageKey);
				}
				new Promise((resolve, reject) => {
					data.forEach(async (item, index) => {
						const comment = item.comment;
						if (comment.storeageFiles && comment.storeageFiles.length > 0) {
							await this.saveFile(comment.storeageFiles)
								.then(res => {
									const newFiles = res;
									comment.storeageFiles = newFiles;
								});
						}
						if (index === data.length - 1) {
							resolve(data);
						}
					});
				}).then(storeageData => {
					uni.setStorage({
						key: this.storageKey,
						data: storeageData,
						success: function() {
							console.log('success');
							uni.$u.toast("缓存成功")
						}
					});
				});
			},
			getResult(value) {

				let result = "";

				if (value.improveState == 2) {
					result = "不合格";
				} else if (value.improveState == 1) {
					result = "合格";
				}

				if (value.light != '' && value.light != null) {
					result = result + "\n亮点：" + value.light
				}

				if (value.content != '' && value.content != null) {
					console.log(value.content)

					result = result + "\n问题：" + value.content
				}

				return result;

			},
			getSrc(state) {
				if (state == 1) {
					return "/static/images/icon_du_lv.png";
				} else {
					return "/static/images/icon_school_lv.png";
				}
			},
			viewFile() {
				if (this.fileNum == 0) {
					this.$u.toast("暂无实证资料");
					return;
				}
				const comment = this.comments[this.index];
				const fileUrls = {
					imgUrls: comment.imgUrls,
					voiceUrls: comment.voiceUrls,
					videoUrls: comment.videoUrls,
				}
				this.$tab.navigateTo("/pages/empirical-file/empirical-file?fileUrls=" + encodeURIComponent(JSON
					.stringify(fileUrls)));
			},
			getFileNum() {
				let num = 0;
				const comment = this.comments[this.index]
				console.log(comment)
				num += comment.imgUrls.length;
				num += comment.voiceUrls.length;
				num += comment.videoUrls.length;
				this.fileNum = num;
			},
			changeNaBtnTitle(text) {
				var pages = getCurrentPages();
				var page = pages[pages.length - 1];
				var currentWebview = page.$getAppWebview();
				var tn = currentWebview.getStyle().titleNView;

				if (text == "提交了") {
					tn.buttons[0].width = 0;
					currentWebview.setStyle({
						titleNView: tn
					});
				} else {
					tn.buttons[0].text = text;
					currentWebview.setStyle({
						titleNView: tn
					});
				}
			},
			async uploadFile(files) {
				const saveFiles = deepClone(files);
				let urlId = [];
				return new Promise((resolve, reject) => {
					console.log("开始上传")
					if (saveFiles) {
						const length = saveFiles.length;
						saveFiles.forEach((file, index) => {
							uni.uploadFile({
								url: this.uploadUrl,
								files: [file],
								success: (res) => {
									if (res.statusCode === 200) {
										const resData = JSON.parse(res
											.data);
										urlId = [
											...urlId,
											...resData.urlId
										]
										if (urlId.length === length) {
											resolve(urlId)
										}
									} else {
										uni.$u.toast("实证材料上传失败");
									}
								},
								fail: (err) => {
									console.log(err)
									uni.$u.toast("实证材料上传失败");
									resolve1("");
								}
							})
						});
					} else {
						resolve()
					}
				});
			},

		},
		onLoad: function(option) {

			console.log(option)
			if (Object.keys(option).length > 0) {
				this.activityId = option.activityId
				this.targetId = option.targetId
				console.log(option.activityStatus)
				if (option.activityStatus === "待审核" || option.activityStatus === "已通过" || option.activityStatus ===
					"未通过") {
					this.savedFlag = true
				}

				uni.setNavigationBarTitle({
					title: option.title
				})
			}

			let deviceId = uni.getStorageSync("deviceId");
			// key = deviceId_userName_activityId_targetId_schoolId
			this.storageKey =
				`${deviceId}_${this.$store.state.user.name}_${this.activityId}_${this.targetId}`;

			this.getTargetContent();
		},
		onNavigationBarButtonTap(e) {

			// 点击导航栏自定义按钮
			this.submit()
		}
	}
</script>

<style lang="scss" scoped>
	.record-container {
		font-size: 20px;

		.swiper {
			width: 100vw;
			min-height: 100vh;
		}

		.title-height {
			height: 7vh;
			line-height: 7vh;
			background-color: #F2F2F0;
		}

		.content {
			min-height: 7vh;
			background-color: #fff;
		}

		.pl-12 {
			padding-left: 12px;

		}

		.radio {
			padding-left: 10px;
		}

		.media {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 25px;
			display: flex;
			background-color: #fff;

			.media-btn {
				width: 25vw;
			}
		}
	}

	/deep/ .is-disabled {
		background-color: #ffffff !important;
		color: #0d0d0d !important;
	}
</style>